package request1_p2p;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;



public class COrderSubscriber implements Observer {
    private List<Merchant> subscribers=new ArrayList<>();
    private double suitableDistance=5;
    public COrderSubscriber(List<Merchant> subscribers){
        this.subscribers=subscribers;
    }

    public List<Merchant> getSubscribers() {
        return subscribers;
    }

    public void setSubscribers(List<Merchant> subscribers) {
        this.subscribers = subscribers;
    }

    @Override
    public void update(Observable o, Object arg) {
        COrderPublisher dispatch=(COrderPublisher) o;
        COrderEvent orderEvent=(COrderEvent)arg;
        Consumer consumer=dispatch.getConsumer();
        Merchant final_merchant=null;
        int ID=orderEvent.getMerchant().getId();
        String orderContent="";
        for(Product p:orderEvent.getProductList()){
            orderContent+=p.getName()+" ";
        }
        for(Merchant merchant:subscribers){
            if(merchant.getId()==ID){
                Double distance=Math.sqrt(Math.pow((merchant.getLocation()[0]-consumer.getLocation()[0]),2)
                        +Math.pow((merchant.getLocation()[1]-consumer.getLocation()[1]),2));
                if(distance<suitableDistance){
                    final_merchant=merchant;
                    System.out.println("商家"+merchant.getName()+"您好！");
                    System.out.println("接收到来自"+dispatch.getConsumer().getName()+"的订单任务:");
                    System.out.println(orderContent);
                    System.out.println("用户距您："+distance+"公里");
                    System.out.println("-----------------------------");
                }
            }
        }
        orderEvent.setMerchant(final_merchant);
        System.out.println("事件分发完毕，最终分配的商家为："+orderEvent.getMerchant().getName());
    }
}
